import csv
def search_consumption_data():
    # 尝试用不同编码读取CSV文件
    encodings = ['utf-8', 'gbk', 'gb2312', 'utf-16']

    for encoding in encodings:
        try:
            with open('xiaofei.csv', mode='r', encoding=encoding) as file:
                reader = csv.DictReader(file)
                data = [row for row in reader]
                break  # 如果成功读取就跳出循环
        except UnicodeDecodeError:
            continue  # 尝试下一种编码

    if not data:
        print("无法读取文件，请检查文件编码格式")
        return

    # 获取用户输入
    while True:
        user_input = input("请输入你要查询的城市和项目以逗号分隔：\n")
        inputs = [item.strip() for item in user_input.split(',')]

        if len(inputs) >= 2:
            break
        print("输入格式不正确，请按照'省份, 项目1, 项目2,...'的格式输入")

    province = inputs[0]
    items = inputs[1:]

    print(f"你输入的城市是：{province}")

    # 查找匹配的数据
    found = False
    for row in data:
        # 检查地区列是否匹配，不区分大小写
        if row.get('地区', '').lower() == province.lower():
            found = True
            for item in items:
                # 检查项目是否存在，不区分大小写
                matched_key = None
                for key in row.keys():
                    if key.lower() == item.lower():
                        matched_key = key
                        break

                if matched_key:
                    print(f"{matched_key}的消费金额为: {row[matched_key]}")
                else:
                    print(f"未找到项目: {item}")
            break

    if not found:
        print(f"未找到省份: {province}")


if __name__ == "__main__":
    search_consumption_data()